package sunbao.ido.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.EnumerablePropertySource;
import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Properties;

/**
 * \* User: MeiZhongHao
 * \* Date: 2018-11-12
 * \* Time: 17:12
 * \* Description:
 * \  使用EnvironmentPostProcessor加载外部配置资源
 */
@Configuration
@ConditionalOnClass({ConfigClient.class})
public class ConfigAutoConfiguration implements EnvironmentPostProcessor {

    private static final String BINDER_BEAN_NAME = ConfigurationPropertiesBindingPostProcessor.class.getName();

    // 加载外部配置资源
    @Override
    public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment, SpringApplication springApplication) {
        configurableEnvironment.getPropertySources().addLast(new EnumerablePropertySource<String>(ConfigClient.class.getName()) {
            @Override
            public String[] getPropertyNames() {
                Properties properties = ConfigClient.getProperties();
                return properties.stringPropertyNames().toArray(new String[properties.size()]);
            }

            @Override
            public String getProperty(String name) {
                return ConfigClient.getString(name);
            }
        });
    }

    /**
     * 声明BeanFactoryPostProcessor处理器
     *
     * @return
     */
    @Bean
    public ConfigAutoConfiguration.ConfigBeanFactoryPostProcessor configBeanFactoryPostProcessor() {
        return new ConfigAutoConfiguration.ConfigBeanFactoryPostProcessor();
    }

    /**
     * 声明BeanPostProcessor处理器
     *
     * @return
     */
    @Bean
    public ConfigAutoConfiguration.RegisterConfigChangeListenerBeanPostProcessor registerConfigChangeListenerBeanPostProcessor() {
        return new ConfigAutoConfiguration.RegisterConfigChangeListenerBeanPostProcessor();
    }

    /**
     * 前置处理器，后置处理器 在bean 初始化完成后，将相关的ConfigChangeListener注册至ConfigClient
     * 适合自定义监听器，定义一些配置更新后，自己需要做的其他操作
     */
    static class RegisterConfigChangeListenerBeanPostProcessor implements BeanPostProcessor {
        @Override
        public Object postProcessBeforeInitialization(Object bean, String beanName) {
            return bean;
        }

        @Override
        public Object postProcessAfterInitialization(Object bean, String beanName) {
            if (bean instanceof ConfigChangeListener) {
                ConfigClient.addConfigChangeListener((ConfigChangeListener) bean);
            }
            return bean;
        }
    }

    /**
     * bean工厂的bean属性处理容器，说通俗一些就是可以管理我们的bean工厂内所有的beandefinition（未实例化）数据，可以随心所欲的修改属性。
     * 添加配置更新事件监听
     */
    static class ConfigBeanFactoryPostProcessor implements BeanFactoryPostProcessor {
        @Override
        public void postProcessBeanFactory(final ConfigurableListableBeanFactory beanFactory) {
            ConfigClient.addConfigChangeListener(event -> {
                String[] var2 = beanFactory.getBeanDefinitionNames();
                int var3 = var2.length;

                for (int var4 = 0; var4 < var3; ++var4) {
                    String beanName = var2[var4];
                    ConfigBeanFactoryPostProcessor.this.processConfigProperties(beanFactory, beanFactory.getBean(beanName), beanName);
                }

            });
        }

        private void processConfigProperties(ConfigurableListableBeanFactory beanFactory, Object bean, String beanName) {
            if (bean != null) {
                this.processValueAnnotation(beanFactory, bean, beanName);
                this.processConfigurationPropertiesAnnotation(beanFactory, bean, beanName);
            }
        }

        private void processValueAnnotation(final ConfigurableListableBeanFactory beanFactory, final Object bean, String beanName) {
            Class<?> clazz = bean.getClass();
            ReflectionUtils.doWithMethods(clazz, new ReflectionUtils.MethodCallback() {
                @Override
                public void doWith(Method method) {
                    Value value = AnnotationUtils.getAnnotation(method, Value.class);
                    if (value != null && method.getParameterTypes().length == 1) {
                        String configValue = beanFactory.resolveEmbeddedValue(value.value());
                        Object newValue = beanFactory.getTypeConverter().convertIfNecessary(configValue, method.getParameterTypes()[0]);
                        ReflectionUtils.invokeMethod(method, bean, new Object[]{newValue});
                    }
                }
            });
            ReflectionUtils.doWithFields(clazz, new ReflectionUtils.FieldCallback() {
                @Override
                public void doWith(Field field) {
                    Value value = AnnotationUtils.getAnnotation(field, Value.class);
                    if (value != null) {
                        String configValue = beanFactory.resolveEmbeddedValue(value.value());
                        Object newValue = beanFactory.getTypeConverter().convertIfNecessary(configValue, field.getType());
                        ReflectionUtils.makeAccessible(field);
                        ReflectionUtils.setField(field, bean, newValue);
                    }
                }
            });
        }

        private void processConfigurationPropertiesAnnotation(ConfigurableListableBeanFactory beanFactory, Object bean, String beanName) {
            ConfigurationPropertiesBindingPostProcessor processor = (ConfigurationPropertiesBindingPostProcessor) beanFactory.getBean(ConfigAutoConfiguration.BINDER_BEAN_NAME);
            processor.postProcessBeforeInitialization(bean, beanName);
        }
    }
}